package com.ericsson.mna.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.ericsson.mna.model.bs.TaskServices;
import com.ericsson.mna.model.pojo.AssignTask;
import com.ericsson.mna.model.pojo.DBConf;
import com.ericsson.mna.model.pojo.Task;

/**
 * Servlet implementation class TaskController
 */
@WebServlet("/TaskController")
public class TaskController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TaskController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession(false);
		if(session!=null)
		{
		    ArrayList<Task> taskList=(ArrayList<Task>)session.getAttribute("taskList");
		    for(Task t:taskList)
		    {
		    	System.out.println("Task ::::"+t);
		    	String taskId=t.getTask_Id();
		    	//String taskId=request.getParameter("taskId"));
		    	if(taskId.equalsIgnoreCase(request.getParameter("taskId")))
		    	{

		    		session.setAttribute("task",t);
		    		RequestDispatcher rd=request.getRequestDispatcher("taskDetail.jsp");
		    		rd.forward(request, response);
		    		break;
		    	}
		    }
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		System.out.println("Task Controller Called........");
		String pageName=request.getParameter("pageName");
		System.out.println(pageName);
		HttpSession session=null;
		Properties prop=new Properties();
		prop.load(getServletContext().getResourceAsStream("/view/resources/prop/DbConf.properties"));
		DBConf dbconf=new DBConf();
		dbconf.setDriverName(prop.getProperty("driverName"));
		dbconf.setPassword(prop.getProperty("password"));
		dbconf.setUrl(prop.getProperty("url"));
		dbconf.setUserName(prop.getProperty("userName"));
		//System.out.println("Configurations :::"+dbconf);
		RequestDispatcher rd=null;
		if(pageName.equalsIgnoreCase("viewTask"))
		{
			session=request.getSession(false);
			if(session != null)
			{
				//System.out.println("Task Controller Called........");
				String userName=session.getAttribute("userId").toString();
				//System.out.println("User Name is::"+userName);
				TaskServices ts=new TaskServices(dbconf);
				ArrayList<Task> taskList=new ArrayList<Task>();
				taskList=ts.getTaskList(userName);
				System.out.println("From Task Controller::"+taskList);
				request.setAttribute("taskList", taskList);
				session.setAttribute("taskList", taskList);
				rd=request.getRequestDispatcher("viewTask.jsp");
				rd.forward(request, response);
			}
		}
		else if(pageName.equalsIgnoreCase("taskDetailUpdate"))
		{
			AssignTask assignTask = new AssignTask();
			assignTask.setComments(request.getParameter("comments"));
			try {
				assignTask.setTaskCompletedOn(new java.sql.Date((new SimpleDateFormat("MM/dd/yyyy").parse(request.getParameter("completedOn")).getTime())));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			assignTask.setStatus(request.getParameter("status"));
			assignTask.setTask_id(request.getParameter("taskId"));

			TaskServices taskServ=new TaskServices(dbconf);
			PrintWriter out=response.getWriter();
			response.setContentType("text/html");
			boolean isUpdate=taskServ.updateTask(assignTask);

			if(isUpdate)
			{
				out.println("<script language=javascript>");
				out.println("<!--");
				out.println("alert('Info: Task status has been updated');");
				out.print("window.location='tab.jsp'");
				out.println("//-->");
				out.println("</script>");
			}
			else
			{
				out.println("<script language=javascript>");
				out.println("<!--");
				out.println("alert('Error: Unable to assigned Task Status');");
				out.print("window.location='tab.jsp'");
				out.println("//-->");
				out.println("</script>");
			}
		}

		else if(pageName.equalsIgnoreCase("assignTask"))
		{
			AssignTask assignTask = new AssignTask();
			assignTask.setTitle(request.getParameter("Title"));
			assignTask.setCategory(request.getParameter("category"));
			assignTask.setAssignedTo(request.getParameter("AssignTo"));
			assignTask.setTaskDescription(request.getParameter("TaskDetails"));
			assignTask.setPriority(request.getParameter("Priority"));
			
			try {
				assignTask.setTaskEndDate(new java.sql.Date((new SimpleDateFormat("MM/dd/yyyy").parse(request.getParameter("Deadline")).getTime())));
			} catch (ParseException e) {

				e.printStackTrace();
			}
			assignTask.setStatus("Open");
			assignTask.setVisibility("All");
			assignTask.setDomain(request.getParameter("Domain"));
			assignTask.setSubDomain(request.getParameter("SubDomain"));
			assignTask.setAssignedBy((String)request.getSession().getAttribute("userId"));
			Part part = request.getPart("attachment");
			InputStream inputStream = part.getInputStream();

			TaskServices taskServ=new TaskServices(dbconf);
			PrintWriter out=response.getWriter();
			response.setContentType("text/html");

			int recd = taskServ.assignTask(assignTask, inputStream);
			if(recd>0){
				out.println("<script language=javascript>");
				out.println("<!--");
				out.println("alert('Info: Task has been assigned');");
				out.print("window.location='tab.jsp'");
				out.println("//-->");
				out.println("</script>");
			}else{
				out.println("<script language=javascript>");
				out.println("<!--");
				out.println("alert('Error: Unable to assign Task');");
				out.print("window.location='tab.jsp'");
				out.println("//-->");
				out.println("</script>");
			}
		}

		else if(pageName.equalsIgnoreCase("viewTaskStatus"))
		{
			session=request.getSession(false);
			String userId=session.getAttribute("userId").toString();
			TaskServices ts=new TaskServices(dbconf);
			ArrayList<Task> taskList=new ArrayList<Task>();
			taskList=ts.getTaskStatus(userId);
			System.out.println("From Task Controller::"+taskList);
			request.setAttribute("taskList", taskList);
			session.setAttribute("taskList", taskList);
			rd=request.getRequestDispatcher("viewTaskStatus.jsp");
			rd.forward(request, response);



		}
		//Task Status will be updated here
		else if(pageName.equalsIgnoreCase("updateTaskStatus"))
		{
			int count = (int) (request.getSession().getAttribute("totalTask"));
			HashMap<String, String> taskStatusMap = new HashMap<String, String>();
			for(int i=0; i<count; i++){
				System.out.println(request.getParameter("taskName"+i) +"::"+request.getParameter("action"+i));
				String status = request.getParameter("action"+i);
				if(status!=null){
					taskStatusMap.put(request.getParameter("taskName"+i), status);
				}
			}

			TaskServices taskServ=new TaskServices(dbconf);
			PrintWriter out=response.getWriter();
			response.setContentType("text/html");
			boolean isUpdate=false;
			try {
				isUpdate = taskServ.updateTaskStatus(taskStatusMap);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if(isUpdate)
			{
				out.println("<script language=javascript>");
				out.println("<!--");
				out.println("alert('Info: Task status has been updated');");
				out.print("window.location='tab.jsp'");
				out.println("//-->");
				out.println("</script>");
			}
			else
			{
				out.println("<script language=javascript>");
				out.println("<!--");
				out.println("alert('Error: Unable to assigned Task Status');");
				out.print("window.location='tab.jsp'");
				out.println("//-->");
				out.println("</script>");
			}
		}
	}
	}


